import React, { JSX } from 'react';
import { NulCommonOperations, NulDialog, NulFormItem } from '../../components/NulDialog';
import { Autocomplete, TextField } from '@mui/material';
import { Warehouse } from '../../actions/InventoryManagement';

interface SwitchInventoryDialogProps {
  open: boolean;
  onClose: () => void;
  onResult: (inventoryId: number) => void;
  warehouseEntries: Warehouse[];
}

interface WarehouseOption {
  label: string;
  id: number;
}

function buildOptions(warehouseEntries: Warehouse[]): WarehouseOption[] {
  const result: WarehouseOption[] = [];
  for (let i = 0; i < warehouseEntries.length; ++i) {
    result.push({ label: warehouseEntries[i].name, id: warehouseEntries[i].id });
  }
  return result;
}

function SwitchInventoryDialog(props: SwitchInventoryDialogProps): JSX.Element {
  const { open, onClose, onResult, warehouseEntries } = props;

  const options: WarehouseOption[] = buildOptions(warehouseEntries);

  const [value, setValue] = React.useState<WarehouseOption | null>(null);

  const handlePositiveClicked = () => {
    if (value !== null) {
      onResult(value.id);
    }
    onClose();
  };

  return (
    <NulDialog
      open={open}
      onClose={onClose}
      title='Switch Inventory'
      operations={
        <NulCommonOperations
          onPositiveClicked={handlePositiveClicked}
          onNegativeClicked={onClose}
        />
      }
    >
      <NulFormItem hint='Inventory' component={
        <Autocomplete
          options={options}
          getOptionLabel={option => option.label}
          renderInput={(param) => <TextField {...param} />}
          value={value}
          onChange={(event, value) => { setValue(value); }}
          fullWidth={true}
          size='small'
        />
      } />
    </NulDialog>
  );
}

export default SwitchInventoryDialog;